import React, { Component } from 'react';
import { Button, Form, Input, Checkbox, Switch, Spin, Select, Row, Col } from 'antd'
import { messages } from "share/common";
import { connect } from 'react-redux';
import Priority from 'components/template/priority';
const FormItem = Form.Item;
const Group = Checkbox.Group;
const { Option } = Select;
import 'styles/supplier-management/new-consumer-management/edit-frams/edit-frame.scss'
import NewConsumerServer from '../new-consumer-server'
import { message } from "antd/lib/index";
import ConsumerUtil from '../consumer-util';

@Form.create()
class TravelNoOneEditFrame extends Component {

  constructor(props) {
    super(props);
    this.isLock = false;
    this.openTypeOptions = [
      { label: messages('supplier-1.key88')/*国内机票*/, value: 'withFlightSupplier' },
      { label: messages('supplier-1.key254')/*国内酒店*/, value: 'withHotelSupplier' }
    ];

    this.approvalOptions = [
      { label: messages('supplier-1.key80')/*机票*/, value: 'withFlightApproval' },
      { label: messages('supplier-1.key81')/*酒店*/, value: 'withHotelApproval' }
    ];

    this.paymentCycles = [
      {
        label: messages('supplier-1.key183')/*自然月*/,
        value: 'M'
      },
      {
        label: messages('supplier-1.key184')/*固定日*/,
        value: 'D'
      },
    ]
    this.accountPeriodDayOptions = new Array(28).fill({}).map((item, i) => {
      item = {
        label: i + 1,
        value: i + 1,
      }
      return item
    })
    this.appIds = ["ssoAppId", "syncAppId", "dataAppId"];
    this.appSecrets = ["ssoAppSecret", "syncAppSecret", "dataAppSecret"];
    this.appTypes = [messages('supplier-1.key255')/*单点登录*/, messages('supplier-1.key256')/*审批单/组织架构同步*/, messages('supplier-1.key257')/*消费明细 */];

    this.state = {
      editData: {},
      loading: false,
      isNew: false,
      priDefalultValue: {},
    }
  }

  componentWillMount() {
    const { params, tenant } = this.props;
    const initValue = ConsumerUtil.initPriorityData(this.props);
    if (params.companyInfos) {
      initValue.distribution = {
        companies: params.companyInfos ? params.companyInfos : []
      }
    }
    this.setState({
      editData: params,
      isNew: params.levelCode ? false : true,
      priDefalultValue: initValue
    }, this.props.form.resetFields);
  }

  onPriorityChange = (values) => {
    this.setState({
      priDefalultValue: values,
    })
  }

  onCancelEdit = () => {
    this.props.close();
    this.props.form.resetFields();
  };

  onSubmitEdit = () => {
    if (this.isLock) {
      return;
    }
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { priDefalultValue, isNew, editData } = this.state;
        const authData = JSON.parse(JSON.stringify(priDefalultValue));
        const { tenant } = this.props;
        if (!authData) {
          message.error(messages('supplier-1.key185')/*请填写所属组织*/);
          return;
        }
        if (!authData.distribution && authData.levelCode != 'COMPANY') {
          message.error(messages('supplier-1.key186')/*启用公司不支持通用*/);
          return;
        }
        if (authData.levelCode != 'COMPANY' && authData.distribution.companies.length <= 0) {
          message.error(messages('supplier-1.key187')/*请填写公司*/);
          return;
        }
        const pri = {
          ...authData,
          companies: authData.distribution ? authData.distribution.companies.map(item => item.id) : [],
        }
        delete pri.distribution;

        let upParams = Object.assign({}, values, pri);
        const setApprovalOptions = enable => this.approvalOptions.map(item => item.value).map(item => { upParams[item] = enable.includes(item)});

        upParams.tenantId = tenant.id;
        upParams.tenantName = tenant.tenantName;
        upParams.vendorCompanyId = upParams.vendorCompanyId;


        this.openTypeOptions.map(item => item.value).map(item => upParams[item] = false);

        upParams.openType.forEach((item) => {
          upParams[item] = true;
        })
        setApprovalOptions(upParams.approvalEnabled);
        delete upParams.approvalEnabled;

        if (!isNew) {
          upParams = Object.assign({}, editData, upParams);
        }

        delete upParams.openType;
        delete upParams.approveType;
        delete upParams.parameterConfig;
        //账期功能这个迭代不上了
        // if(upParams.reconciliationType === "M"){
        //   upParams.reconciliationDate = "";
        // }
        this.isLock = true;
        NewConsumerServer(this).saveTravelnoone(upParams).then(res => {
          this.isLock = false;
          if (!res.data.passFlag && res.data.message) {
            message.error(res.data.message);
          } else {
            this.props.close(true);
          }
        });
      }
    })
  };


  render() {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { editData, loading, isNew, priDefalultValue } = this.state;
    const initialParameterConfig = this.appIds.map((item,idx)=>editData[item] && idx).filter(item => typeof item === "number");
    const parameterConfig = getFieldValue("parameterConfig") || initialParameterConfig;
    const initialOpenType = [];
    this.openTypeOptions.forEach (({value}) => {
      if(editData[value]){
        initialOpenType.push(value);
      }
    })

    const initialApproval = [];
    this.approvalOptions.forEach (({value}) => {
      if(editData[value]){
        initialApproval.push(value);
      }
    })

    const formLayout = {
      labelCol: { span: 6, offset: 1 },
      wrapperCol: { span: 14 }
    };


    return (
      <div className='edit-frame'>
        <Spin spinning={loading}>
          <Form className="new-form">
            <FormItem label={messages('common.column.status')/*状态*/} {...formLayout}>
              {
                getFieldDecorator('enabled', {
                  initialValue: editData.enabled || false,
                  valuePropName: 'checked',
                })(
                  <Switch />
                )
              }
            </FormItem>
            <Priority
              top='TENANT'
              formItemLayout={formLayout}
              disabledTop={!isNew}
              companyProps={{ disabled: !isNew }}
              defaultValue={priDefalultValue}
              onChange={this.onPriorityChange}
            />
            <h3 style={{ borderBottom: 0 }}>
              <div className='other-rule-edit-title'>
                {messages('supplier-1.key189')/*服务商参数设置*/}
              </div>
            </h3>
            <FormItem label="Company ID" {...formLayout}>
              {
                getFieldDecorator('vendorCompanyId', {
                  initialValue: editData.vendorCompanyId || '',
                  rules: [
                    { required: true, message: messages('supplier-1.key193')/*必填*/ }
                  ]
                })(
                  <Input />
                )
              }
            </FormItem>
            <FormItem label="Company Name" {...formLayout}>
              {
                getFieldDecorator('vendorCompanyName', {
                  initialValue: editData.vendorCompanyName || '',
                  rules: [
                    { required: true, message: messages('supplier-1.key193')/*必填*/ }
                  ]
                })(
                  <Input />
                )
              }
            </FormItem>
            <FormItem label={messages('supplier-1.key258')/*顶级部门ID*/} {...formLayout}>
              {
                getFieldDecorator('topDeptNo', {
                  initialValue: editData.topDeptNo || '',
                })(
                  <Input />
                )
              }
            </FormItem>
            <FormItem label="System ID" {...formLayout}>
              {
                getFieldDecorator('vendorSystemId', {
                  initialValue: editData.vendorSystemId || ''
                })(
                  <Input />
                )
              }
            </FormItem>
            <FormItem label={messages('supplier-1.key259')/*对接参数配置*/} {...formLayout}>
              {
                getFieldDecorator('parameterConfig',{initialValue:initialParameterConfig})(
                  <Checkbox.Group style={{ width: '100%', marginTop: '20px' }} >
                    <Row>
                      <Col span={4}>
                        <Checkbox value={0}>{this.appTypes[0]}</Checkbox>
                      </Col>
                      <Col span={7}>
                        <Checkbox value={1}>{this.appTypes[1]}</Checkbox>
                      </Col>
                      <Col span={4}>
                        <Checkbox value={2}>{this.appTypes[2]}</Checkbox>
                      </Col>
                    </Row>
                  </Checkbox.Group>)
              }
            </FormItem>
            {
              parameterConfig && parameterConfig.map(item => {
                return <div>
                  <FormItem label="App ID" {...formLayout}>
                    {
                      getFieldDecorator(this.appIds[item], {
                        initialValue: editData[this.appIds[item]] || '',
                        rules: [
                          { required: true, message: messages('supplier-1.key193')/*必填*/ }
                        ]
                      })(
                        <Input placeholder={`${this.appTypes[item]}App ID`} key={item} />
                      )
                    }
                  </FormItem>
                  <FormItem label="App Secret" {...formLayout}>
                    {
                      getFieldDecorator(this.appSecrets[item], {
                        initialValue: editData[this.appSecrets[item]] || '',
                        rules: [
                          { required: true, message: messages('supplier-1.key193')/*必填*/ }
                        ]
                      })(
                        <Input placeholder={`${this.appTypes[item]}App Secret`} key={item} />
                      )
                    }
                  </FormItem>
                </div>
              })
            }
            <h3 style={{ borderBottom: 0 }}>
              <div className='other-rule-edit-title'>
                {messages('supplier-1.key545')/*申请单相关配置*/}
              </div>
            </h3>
            <FormItem label={messages('supplier-1.key197')/*行程上可选该服务商*/} {...formLayout}>
              {
                getFieldDecorator('approvalEnabled', {
                  initialValue: initialApproval || []                
                })(
                  <Group options={this.approvalOptions} />
                )
              }
            </FormItem>

            <h3 style={{ borderBottom: 0 }}>
              <div className='other-rule-edit-title'>
                {messages('supplier-1.key194')/*服务商应用类型设置*/}
              </div>
            </h3>
            <FormItem style={{ display: "flex", alignItems: 'center' }} label={messages('supplier-1.key195')/*应用类型*/} {...formLayout}>
              {
                getFieldDecorator('openType', {
                  initialValue: initialOpenType || []
                })(<Group options={this.openTypeOptions} />)
              }
            </FormItem> 
            {/*留hash坐记录，影响到初始化了*/}
          </Form>
        </Spin>
        <br /><br /><br /><br />
        <div className='affix-bottom'>
          <Button type="primary" loading={loading} onClick={this.onSubmitEdit}>
            {messages('common.ok')/*确定*/}
          </Button>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <Button onClick={this.onCancelEdit}>
            {messages('common.cancel')/*取消*/}
          </Button>
        </div>
      </div>
    )
  }
}


TravelNoOneEditFrame.getEditData = record => {
  const params = JSON.parse(JSON.stringify(record));
  return params;
};

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
  }
}

export default connect(mapStateToProps)(TravelNoOneEditFrame);
